<html>

    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" type="text/css" href="../styles/style_push.css" />
	<link href="../styles/main.css" rel="stylesheet" type="text/css" />
    </head>

        <ul>
            <li><a class="first" href="../index.php">Accueil</a></li>
        </ul>
	    
<?php

    include '../database.php';
            
    $con = mysql_connect($hostname,$username,$password) or die('Could not connect to database : ' . mysql_error());
	
    mysql_select_db($database);
	    
    //echo "<br>Connected to database " . $database;
	    
    $query = "SELECT * FROM $devicestable"; 
    
    $result = mysql_query($query) or die('Error executing query :<br>'.$query.'<br>'.mysql_error());
	    
    // Put your private key's passphrase here:
    $passphrase = '78692110';
    
    // Put your alert message here:
    $message = $_POST['pushmessage'];

    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
    
    // Open a connection to the APNS server
    $fp = stream_socket_client(
            'ssl://gateway.push.apple.com:2195', $err,
            $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
    
    if (!$fp)
            exit("Failed to connect: $err $errstr" . PHP_EOL);
    
    //echo '<br>Connected to APNS' . PHP_EOL;
    
    ob_flush();
    flush();
        
    // Create the payload body
    $body['aps'] = array(
            'alert' => $message,
            'sound' => 'default',
            "badge" => 1
            );
    
    $body['type'] = $_POST['pushtype'];;
        
    // Encode the payload as JSON
    $payload = json_encode($body);
    
    $i = 0;
    while($data = mysql_fetch_assoc($result)) 
    {
	$deviceTokenTab[$i] = $data['devicetoken'];
	$deviceNameTab[$i] = $data['devicename'];
	$i++;
    }
    
?>
    <TABLE <table id="table-design"> 
	<thead> 
            <TH>Status</TH> 
        </thead>
	<tbody>
<?php

    for($i = 0; $i<count($deviceTokenTab); $i++) {
	
	$deviceToken = $deviceTokenTab[$i];
	$deviceName = $deviceNameTab[$i];
	
	//echo '<br>Send push to <b>' . $deviceToken . '</b>';
	
	// Build the binary notification
	$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
	
	// Send it to the server
	$result = fwrite($fp, $msg, strlen($msg));
	
	echo '<tr>';
	if (!$result)
		echo '<td>'.'Message not delivered to ' . $deviceName .'</td>' . PHP_EOL;
	else
		echo '<td>'.'Message successfully delivered to ' . $deviceName .'</td>' . PHP_EOL;
	echo '</tr>';
	ob_flush();
	flush();
	    
    }

   // Close the connection to the server
    fclose($fp);
?>
	</tbody>
    </TABLE>
<?php

    echo '<p><a href="pushmanager.php">Retour</a></p>';
    
    mysql_close($con);

?>

</html>